//
//  SYBoardZiYuanViewController.m
//  SanYiTeaching
//
//  Created by 郑浩然 on 2019/9/17.
//  Copyright © 2019年 SanYi. All rights reserved.
//

#define kIsEqualToString(msg) [interactionModel.suffix isEqualToString:msg]

#import "SYBoardZiYuanViewController.h"
#import "SYBoardCollectionViewCell.h"
#import "SYBoardCollectionTableViewCell.h"

@interface SYBoardZiYuanViewController () <UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UICollectionView *curCollectionView;
@property (copy, nonatomic) NSString *path;
@property (strong, nonatomic) SYInteractionZiYuanModel *ziyuanModel;
@property (strong, nonatomic) SYNoLabel *nolab;
@property (weak, nonatomic) IBOutlet UITableView *curTableView;


@end

@implementation SYBoardZiYuanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
}

- (void)initSubView { //400
//    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
//    CGFloat width = (400-20)/3;
//    flowLayout.itemSize = CGSizeMake(width, width);
//    flowLayout.minimumLineSpacing = 10;
//    flowLayout.minimumInteritemSpacing = 10;
//    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
//    [self.curCollectionView setCollectionViewLayout:flowLayout];
//    self.curCollectionView.backgroundColor = [UIColor whiteColor];
//    self.curCollectionView.delegate = self;
//    self.curCollectionView.dataSource = self;
//    [self.curCollectionView registerNib:[UINib nibWithNibName:@"SYBoardCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"SYBoardCollectionViewCell"];
//
//    _nolab = [[SYNoLabel alloc] initWithNameStr:@"暂无资源，请添加" contView:self.view];
//    if (self.dataListArr.count == 0) {
//        _nolab.hidden = NO;
//    } else {
//        _nolab.hidden = YES;
//    }
    
    self.curTableView.delegate = self;
    self.curTableView.dataSource = self;
    [self.curTableView registerCellWithNIbNames:@[@"SYBoardCollectionTableViewCell"]];
    
}

#pragma mark - table
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataListArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SYInteractionZiYuanModel *interactionModel = self.dataListArr[indexPath.row];
    SYBoardCollectionTableViewCell *boardCell = [tableView dequeueReusableCellWithIdentifier:@"SYBoardCollectionTableViewCell" forIndexPath:indexPath];
    [boardCell.headerImageView sd_setImageWithURL:[NSURL URLWithString:interactionModel.icon] placeholderImage:[UIImage imageNamed:@"lunch_center"]];
    boardCell.titleLab.text = [NSString stringWithFormat:@"名字:%@ ",interactionModel.name];
    boardCell.typeLab.text = [NSString stringWithFormat:@"文件类型:%@",interactionModel.suffix];
    
    return boardCell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    SYInteractionZiYuanModel *interactionModel = self.dataListArr[indexPath.row];
        self.ziyuanModel = interactionModel;
        //如果是这种格式，就需要下载
        if (kIsEqualToString(@"ppt")|| kIsEqualToString(@"pptx"))
             {
            [self isLoading:interactionModel.path];
    //        [self selectItemDelegatePath:_path interactionModel:self.ziyuanModel];
            
          //如果是图片，就直接加载
        } else if (kIsEqualToString(@"jpg")||kIsEqualToString(@"png")) {
            [self selectItemDelegatePath:interactionModel.path interactionModel:interactionModel isDownload:NO];
        }
        else {
            [self selectItemDelegatePath:interactionModel.path interactionModel:interactionModel isDownload:NO];
            
        }
}

#pragma mark - 暂时不用了。
#pragma mark - dele
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataListArr.count;
}

- (nonnull __kindof UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    SYInteractionZiYuanModel *interactionModel = self.dataListArr[indexPath.row];
    SYBoardCollectionViewCell *boardCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SYBoardCollectionViewCell" forIndexPath:indexPath];
    boardCell.nameLab.text = [NSString stringWithFormat:@"名字:%@ ",interactionModel.name];
    boardCell.typeLab.text = [NSString stringWithFormat:@"文件类型:%@",interactionModel.suffix];
    if (kIsEqualToString(@"jpg")||kIsEqualToString(@"png")) {
        [boardCell.headerImage sd_setImageWithURL:[NSURL URLWithString:interactionModel.path] placeholderImage:[UIImage imageNamed:@"lunch_center"]];
        
    } else {
        boardCell.headerImage.image = [UIImage imageNamed:@"lunch_center"];
    }
    
    
    return boardCell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    SYInteractionZiYuanModel *interactionModel = self.dataListArr[indexPath.row];
    self.ziyuanModel = interactionModel;
    //如果是这种格式，就需要下载
    if (kIsEqualToString(@"ppt")|| kIsEqualToString(@"pptx"))
         {
        [self isLoading:interactionModel.path];
//        [self selectItemDelegatePath:_path interactionModel:self.ziyuanModel];
        
      //如果是图片，就直接加载
    } else if (kIsEqualToString(@"jpg")||kIsEqualToString(@"png")) {
        [self selectItemDelegatePath:interactionModel.path interactionModel:interactionModel isDownload:NO];
    }
    else {
        [self selectItemDelegatePath:interactionModel.path interactionModel:interactionModel isDownload:NO];
        
    }
    
}
//传入数据，调代理
- (void)selectItemDelegatePath:(NSString *)path interactionModel:(SYInteractionZiYuanModel *)interaction isDownload:(BOOL)isDownload {
    
//    if ([self.delegate respondsToSelector:@selector(selectItemDelegatePath:interactionModel:isDownload:)]) {
//        [self.delegate selectItemPath:path ziyuanModel:interaction isDownload:isDownload];
//    }
    
    if (self.block) {
        self.block(path, interaction,isDownload);
    }
    
}

#pragma mark 判断是否需要下载
- (void)isLoading:(NSString *)urlStr
{
    
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES) objectAtIndex:0];
    NSString *path = [cachesPath stringByAppendingString:[NSString stringWithFormat:@"/%lu.%@",(unsigned long)[urlStr hash],urlStr.pathExtension]];
    _path = path;
    NSData *data = [NSData dataWithContentsOfFile:path];
    
    if (data == nil) {//需要下载
//        [self writeToCacheWithUrl:urlStr];
        [self selectItemDelegatePath:urlStr interactionModel:self.ziyuanModel isDownload:YES];
    } else {//不需要下载
        [self selectItemDelegatePath:_path interactionModel:self.ziyuanModel isDownload:NO];
    }
    
    
}
#pragma mark 写入缓存
- (void)writeToCacheWithUrl:(NSString *)urlStr
{
    
//    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlStr]];
    //创建文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //获取document路径
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
    [fileManager createDirectoryAtPath:[cachesPath stringByAppendingString:@"/Caches"] withIntermediateDirectories:YES attributes:nil error:nil];
    //写入路径
    NSString *path = [cachesPath stringByAppendingString:[NSString stringWithFormat:@"/%lu.%@",(unsigned long)[urlStr hash],urlStr.pathExtension]];
    
//    [data writeToFile:path atomically:YES];
//    _path = path;
    [self requestdataDownLoadFile:path urlstr:urlStr];
    
}
- (void)requestdataDownLoadFile:(NSString *)filePath urlstr:(NSString *)urlStr {
    
   // [MBProgressHUD mj_showMessage:@"正在下载..." toView:self];
    [MBProgressHUD mj_showMessage:@"正在加载..."];
    [SYDownloadFile downloadFileWithUrl:urlStr success:^(id responseObject) {
        [MBProgressHUD mj_hideHUD];
        
        [self selectItemDelegatePath:filePath interactionModel:self.ziyuanModel isDownload:NO];
    } failure:^(NSError *error) {
        [MBProgressHUD mj_hideHUD];
        [MBProgressHUD zr_showError:@"加载失败"];
        
    } progress:^(float progress, long long bytesRead) {
        // [MBProgressHUD mj_hideHUDForView:self.view];
    } savePath:filePath];
    
    
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */


@end
